package cn.com.stary1993.kite.captcha.store.impl;

import cn.com.stary1993.kite.captcha.store.CacheStore;
import cn.com.stary1993.kite.captcha.store.cache.ConCurrentExpiringMap;
import cn.com.stary1993.kite.captcha.store.cache.ExpiringMap;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 本地实现的缓存
 *
 * @author stary1993
 */
public class LocalCacheStore implements CacheStore {

	protected ExpiringMap<String, Object> cache;

	public LocalCacheStore() {
		cache = new ConCurrentExpiringMap<>();
		cache.init();
	}

	@Override
	public Object getCache(String key) {
		return cache.get(key);
	}

	@Override
	public Object getAndRemoveCache(String key) {
		return cache.remove(key);
	}

	@Override
	public boolean setCache(String key, Map<String, Object> data, Long expire, TimeUnit timeUnit) {
		cache.remove(key);
		cache.put(key, data, expire, timeUnit);
		return true;
	}

	/**
	 * 添加缓存数据
	 * @param key key
	 * @param data data
	 * @param expire 过期时间
	 * @param timeUnit 过期时间单位
	 * @return boolean
	 */
	@Override
	public boolean setCache(String key, String data, Long expire, TimeUnit timeUnit) {
		cache.remove(key);
		cache.put(key, data, expire, timeUnit);
		return true;
	}

}
